/*
 * @Author: zyk 997610780@qq.com
 * @Date: 2022-10-14 15:43:58
 * @LastEditors: zyk 997610780@qq.com
 * @LastEditTime: 2022-10-17 11:02:49
 * @FilePath: \fifty-small-projects\41验证码输入框-其他写法\41.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
let code_boxs = document.querySelectorAll('.code_box')
setBoxAction(0)
code_boxs.forEach((box,index)=>{
  box.addEventListener('keydown',function(e){
    // 输入前清空输入框
    code_boxs[index].value = ''
    if (e.key >= 0 && e.key <= 9 && index != code_boxs.length - 1) {
      setTimeout(() => {
        setBoxAction(index + 1)
      }, 10);
    }else if(e.key == 'Backspace'){
      if(index != 0) setTimeout(() => code_boxs[index - 1].focus(), 10)
    }

    if(index >= code_boxs.length - 1){
      code_boxs[index].classList.remove('active')
      setTimeout(() => {
        code_boxs[index].blur()
      }, 10);
    }
  })

  box.addEventListener('keyup',function(e){
    if(index != 0){
      code_boxs[index - 1].classList.remove('active')
    }
  })

  
  box.addEventListener('focus',function(){
    code_boxs.forEach(item=>item.classList.remove('active'))
    setBoxAction(index)
  })

})


function setBoxAction(i){
  code_boxs[i].focus()
  code_boxs[i].classList.add('active')
}